<?php
/**
 * Created by PhpStorm.
 * User: DaveTang
 * Date: 2020/3/3
 * Time: 15:56
 * 用户信息缓存组件
 */

namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Cache\Cache;

class DealUserCacheComponent extends Component
{

    public $_cache_config = 'deal_users';
    public function initialize(array $config)
    {
        parent::initialize($config);
    }

    /**
     * 获取缓存
     */
    public function getVal($user_id)
    {
        $key = 'list_' . $user_id;
        $data = Cache::read($key, $this->_cache_config);
        return empty($data) ? $this->createCache($user_id) : $data;
    }

    /**
     * 创建缓存
     */
    public function createCache($user_id)
    {
        $key = 'list_' . $user_id;
        $controller = $this->_registry->getController();
        $controller->loadModel('DealUsers');
        $data = $controller->DealUsers->find()
            ->where(['user_id' => $user_id])
            ->toArray();
        if(!empty($data)){
            foreach ($data as $k=>$v){
                $cache[$v['deal_type'].'_'.$v['deal_id']][] = ['deal_type'=>$v['deal_type'],'deal_id'=>$v['deal_id'],'id'=>$v['id'],'num'=>$v['num'],'status'=>$v['status'],'begin_time'=>$v['begin_time'],'end_time'=>$v['end_time']];
            }
        }else{
            $cache = null;
        }
        Cache::write($key, $cache, $this->_cache_config);
        return $cache;
    }

    /**
     * 删除缓存
     */
    public function deleteCache($user_id)
    {
        $key = 'list_' . $user_id;
        Cache::delete($key, $this->_cache_config);
        return true;
    }

}